﻿using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

using Eneta.Portal.Common.Repository;

using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.WebParts
{
    [Guid("7e378dea-5d3c-4471-b84b-7c1c7078d9aa")]
    public class IOMenu : WebPart
    {
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Controls.Add(new LiteralControl("<h3><a>Valdkonnad</a></h3>"));

            var repository = new CompanyRepository(SPContext.Current.Web);
            var levels = repository.GetVisibleIoLevels();

            if(levels == null)
            {
                Controls.Add(new LiteralControl("&nbsp;"));
                return;                
            }
            if(levels.Count == 0)
            {
                Controls.Add(new LiteralControl("&nbsp;"));
                return;
            }

            int l1, l3;

            int.TryParse(HttpContext.Current.Request["l1"], out l1);
            int.TryParse(HttpContext.Current.Request["l3"], out l3);

            AddLiteral("<ul>");

            foreach(var level1 in levels)
            {
                AddLiteral("<li");

                if(level1.Id == l1)
                {
                    AddLiteral(" class=\"active\"");
                }

                AddLiteral("><a href=\"/firmad/Lehed/default.aspx?l1=");
                AddLiteral(level1.Id.ToString());
                AddLiteral("\">");
                AddLiteral(level1.Title);
                AddLiteral("</a>");

                if (level1.Level2Items.Count > 0)
                {
                    AddLiteral("<ul class=\"subnav\">");

                    foreach(var level2 in level1.Level2Items)
                        foreach(var level3 in level2.Level3Items)
                        {
                            AddLiteral("<li");
                            if (level3.Id == l3)
                                AddLiteral(" class=\"active\"");
                            AddLiteral("><a href=\"/firmad/Lehed/default.aspx?l3=");
                            AddLiteral(level3.Id + "\">");
                            AddLiteral(level3.Title);
                            AddLiteral("</a></li>");
                        }

                    AddLiteral("</ul>");
                }

                AddLiteral("</li>");
            }

            AddLiteral("</ul>");
        }

        private void AddLiteral(string text)
        {
            Controls.Add(new LiteralControl(text));
        }
    }
}
